import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:wallet_flutter_module/k_line_chart/utils/data_util.dart';
import 'package:wallet_flutter_module/k_line_chart/utils/event_tag_name.dart';
import 'package:wallet_flutter_module/k_line_chart/utils/kline_rule_bean.dart';
import 'package:wallet_flutter_module/k_line_chart/utils/time_bean.dart';
import 'dart:convert';

import 'entity/k_line_entity.dart';
import 'k_chart_widget.dart';

class KLineChartLandPanel extends StatefulWidget {
  @override
  _KLineChartLandPanelState createState() => _KLineChartLandPanelState();
}

class _KLineChartLandPanelState extends State<KLineChartLandPanel>
    with WidgetsBindingObserver {
  static const _channel = const MethodChannel(FLUTTER_TO_NATIVE);

  static const EventChannel _eventChannelPlugin =
      EventChannel(K_Line_Chart_Land_Panel);

  StreamSubscription _streamSubscription;

  int _selectTimePosition = -10;

  List<TimeBean> _timeList = [];

  //主图
  List<KLineRuleBean> _KLineRuleMainList = [];

  int _selectKLineRuleMainPosition = -10;

  bool _showKLineRuleMain = true;

  //副图
  List<KLineRuleBean> _KLineRuleFuList = [];

  int _selectKLineRuleFuPosition = -10;

  bool _showKLineRuleFueMain = true;

  List<KLineEntity> datas;
  bool showLoading = true;
  MainState _mainState = MainState.MA;
  SecondaryState _secondaryState = SecondaryState.MACD;
  bool isLine = true;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addObserver(this);

    _getLocalData();

    if (_streamSubscription == null) {
      _streamSubscription = _eventChannelPlugin
          .receiveBroadcastStream('$K_Line_Chart_Land_Panel')
          .listen(_onEvent, onError: _onError);
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _requireNativeData();
    }
  }

  void _requireNativeData() async {
    try {
      Map<String, Object> map = {
        "param": _timeList[_selectTimePosition].toJson().toString()
      };
      var result = await _channel.invokeMethod("requireNativeData", map);
      print("flutter_result=====$result");
    } catch (e) {
      print(e);
    }
  }

  void _onEvent(event) {
    // Map parseJson = json.decode(event.toString());
    // List list = parseJson['data'];
    List list = json.decode(event.toString());
    print('event: ${event.toString()}');
    datas = list
        .map((item) => KLineEntity.fromJson(item))
        .toList()
        .reversed
        .toList()
        .cast<KLineEntity>();
    DataUtil.calculate(datas);
    showLoading = false;
    setState(() {});
  }

  _onError(error) {}

  @override
  void dispose() {
    if (_streamSubscription != null) {
      _streamSubscription.cancel();
      _streamSubscription = null;
    }
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  void _getLocalData() async {
    //时间数据
    String result = await rootBundle.loadString('json_date/k_line_time');
    Map parseJson = json.decode(result);
    List list = parseJson['data'];
    _timeList = list
        .map((item) => TimeBean.fromJson(item))
        .toList()
        .toList()
        .cast<TimeBean>();
    _selectTimePosition = 0;

    //主图数据
    String mKLineRuleMainResult =
        await rootBundle.loadString('json_date/zhu_tu_rule');
    Map mKLineRuleMainParseJson = json.decode(mKLineRuleMainResult);
    List mKLineRuleMainList = mKLineRuleMainParseJson['data'];
    _KLineRuleMainList = mKLineRuleMainList
        .map((item) => KLineRuleBean.fromJson(item))
        .toList()
        .toList()
        .cast<KLineRuleBean>();

    //副图数据
    String mKLineRuleFuResult =
        await rootBundle.loadString('json_date/fu_tu_rule');
    Map mKLineRuleFuParseJson = json.decode(mKLineRuleFuResult);
    List mKLineRuleFuList = mKLineRuleFuParseJson['data'];
    _KLineRuleFuList = mKLineRuleFuList
        .map((item) => KLineRuleBean.fromJson(item))
        .toList()
        .toList()
        .cast<KLineRuleBean>();

    setState(() {});
  }

  _onScreenOption() async {
    try {
      Map<String, Object> map = {"shareUrl": "https://www.baidu.com"};
      var result = await _channel.invokeMethod("screen_option_p", map);
      print(result);
    } catch (e) {
      print(e);
    }
  }

  Widget _timeItemBuilder(BuildContext context, int index) {
    return GestureDetector(
      onTap: () => {
        _selectTimePosition = index,
        isLine = _timeList[index].isLine,
        showLoading=true,
        setState(() {}),
        _requireNativeData(),
      },
      child: Container(
        height: 40,
        decoration: UnderlineTabIndicator(
            borderSide: BorderSide(
                color: _selectTimePosition == index
                    ? Colors.blue
                    : Colors.transparent)),
        padding: EdgeInsets.only(left: 10, right: 10),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Text(
              _timeList[index].title,
              style: TextStyle(
                  fontSize: 14,
                  decoration: TextDecoration.none,
                  color:
                      _selectTimePosition == index ? Colors.blue : Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  Widget _mainTuItem(BuildContext context, int index) {
    return GestureDetector(
      onTap: () {
        _selectKLineRuleMainPosition = index;
        _showKLineRuleMain = true;
        _mainState = MainState.values[_KLineRuleMainList[index].id];
        setState(() {});
      },
      child: Container(
        height: 26,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Text(
              _KLineRuleMainList[index].title,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 10),
            ),
            Positioned(
                right: 0,
                top: 0,
                child: index == _selectKLineRuleMainPosition
                    ? SizedBox(
                        width: 12,
                        height: 12,
                        child: Image.asset('img/quotes_selected.png'),
                      )
                    : SizedBox())
          ],
        ),
        decoration: BoxDecoration(
            color: index == _selectKLineRuleMainPosition
                ? Colors.white
                : Colors.transparent,
            borderRadius: BorderRadius.circular(2.0),
            border: Border.all(
              color: index == _selectKLineRuleMainPosition
                  ? Colors.blue
                  : Colors.transparent,
              width: 0.5,
            )),
      ),
    );
  }

  Widget _fuTuItem(BuildContext context, int index) {
    return GestureDetector(
      onTap: () {
        _selectKLineRuleFuPosition = index;
        _showKLineRuleFueMain = true;
        _secondaryState = SecondaryState.values[_KLineRuleFuList[index].id];
        setState(() {});
      },
      child: Container(
        height: 26,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Text(
              _KLineRuleFuList[index].title,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 10),
            ),
            Positioned(
                right: 0,
                top: 0,
                child: index == _selectKLineRuleFuPosition
                    ? SizedBox(
                        width: 12,
                        height: 12,
                        child: Image.asset('img/quotes_selected.png'),
                      )
                    : SizedBox())
          ],
        ),
        decoration: BoxDecoration(
            color: index == _selectKLineRuleFuPosition
                ? Colors.white
                : Colors.transparent,
            borderRadius: BorderRadius.circular(2.0),
            border: Border.all(
              color: index == _selectKLineRuleFuPosition
                  ? Colors.blue
                  : Colors.transparent,
              width: 0.5,
            )),
      ),
    );
  }

  Widget _loadKLinePanel() {
    if (showLoading)
      return Container(
          width: double.infinity,
          alignment: Alignment.center,
          child: CircularProgressIndicator());
    else if (datas.isNotEmpty)
      return Stack(children: [
        Container(
          margin: EdgeInsets.symmetric(horizontal: 4),
          width: double.infinity,
          child: KChartWidget(
            datas,
            isLine: isLine,
            mainState: _mainState,
            secondaryState: _secondaryState,
            volState: VolState.VOL,
            fractionDigits: 4,
          ),
        )
      ]);
    else
      return Container(
        alignment: Alignment.center,
        width: double.infinity,
        child: FlatButton(
            onPressed: () {
              showLoading = true;
              _requireNativeData();
              setState(() {});
            },
            child: Text(
              "重新加载",
              style: TextStyle(color: Colors.white),
            ),
            color: Colors.blue),
      );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      primary: false,
      body: Container(
          color: Colors.white,
          child: Column(
            children: [
              Container(
                height: 40,
                color: ColorUtil.color('#F2F2F2'),
                padding: EdgeInsets.only(left: 6),
                child: Row(
                  children: [
                    Expanded(
                        flex: 1,
                        child: SizedBox(
                          child: ListView.builder(
                              itemCount: _timeList.length,
                              shrinkWrap: true,
                              scrollDirection: Axis.horizontal,
                              itemBuilder: _timeItemBuilder),
                        )),
                    GestureDetector(
                      onTap: () => _onScreenOption(),
                      child: Container(
                        width: 60,
                        child: Icon(Icons.fullscreen_exit_rounded,
                            color: Colors.blue, size: 24),
                      ),
                    )
                  ],
                ),
              ),
              Divider(color: Colors.grey, height: 0.5),
              Expanded(
                child: Row(
                  children: [
                    Expanded(flex: 1, child: _loadKLinePanel()),
                    Container(
                      color: ColorUtil.color('#F2F2F2'),
                      alignment: Alignment.center,
                      padding: EdgeInsets.only(bottom: 20),
                      width: 60,
                      child: ListView(
                        children: [
                          Column(
                            children: [
                              Container(
                                height: 20,
                                alignment: Alignment.center,
                                child: Text(
                                  '主图',
                                  style: TextStyle(
                                    color: Colors.grey,
                                    fontSize: 12,
                                    decoration: TextDecoration.none,
                                  ),
                                  textAlign: TextAlign.center,
                                ),
                              ),
                              GestureDetector(
                                onTap: () => {
                                  _showKLineRuleMain = false,
                                  _selectKLineRuleMainPosition = 10,
                                  _secondaryState = SecondaryState.NONE,
                                  setState(() {})
                                },
                                child: Container(
                                  padding: EdgeInsets.symmetric(
                                      vertical: 4, horizontal: 4),
                                  child: Icon(
                                      _showKLineRuleMain
                                          ? Icons.visibility
                                          : Icons.visibility_off,
                                      color: Colors.blue,
                                      size: 18),
                                ),
                              ),
                              ListView.builder(
                                  shrinkWrap: true,
                                  itemCount: _KLineRuleMainList.length,
                                  itemBuilder: _mainTuItem),
                              Divider(color: Colors.grey, height: 0.5),
                              Container(
                                height: 20,
                                alignment: Alignment.center,
                                child: Text(
                                  '副图',
                                  style: TextStyle(
                                    color: Colors.grey,
                                    fontSize: 12,
                                    decoration: TextDecoration.none,
                                  ),
                                  textAlign: TextAlign.center,
                                ),
                              ),
                              GestureDetector(
                                onTap: () => {
                                  _selectKLineRuleFuPosition = -10,
                                  _showKLineRuleFueMain = false,
                                  _secondaryState = SecondaryState.NONE,
                                  setState(() {})
                                },
                                child: Container(
                                  padding: EdgeInsets.symmetric(
                                      vertical: 4, horizontal: 4),
                                  child: Icon(
                                      _showKLineRuleFueMain
                                          ? Icons.visibility
                                          : Icons.visibility_off,
                                      color: Colors.blue,
                                      size: 18),
                                ),
                              ),
                              ListView.builder(
                                  shrinkWrap: true,
                                  itemCount: _KLineRuleFuList.length,
                                  itemBuilder: _fuTuItem),
                            ],
                          )
                        ],
                      ),
                    )
                  ],
                ),
              )
            ],
          )),
    );
  }
}
